const express = require("express");
const multer = require("multer");
const router = express.Router();
const fs = require("fs");
const db = require("../db");
const upload = multer({ dest: "uploads/" });

//上传共享文件
router.post("/img", upload.single("file"), (req, res) => {
  fs.readFile(req.file.path, async (err, data) => {
    if (err) {
      return res.send("上传失败");
    }
    const pathName = `./uploads/article`;
    mkDirs(pathName, () => {
      fs.writeFile(pathName + `/` + req.file.originalname, data, (err) => {
        if (err) {
          return res.send("写入失败");
        }
        fs.unlink(req.file.path, function (err) {
          if (err) {
            throw err;
          }
        });
      });
    });
    await db(
      `update user set headUrl='${
        pathName.substring(1) + `/` + req.file.originalname
      }' where id=${req.user.id}`
    );
    res.send({
      status: 0,
      message: "上传成功",
      url: pathName.substring(1) + `/` + req.file.originalname,
    });
  });
});

function mkDirs(dirname, callback) {
  fs.exists(dirname, function (exists) {
    if (exists) {
      callback();
    } else {
      mkDirs(path.dirname(dirname), function () {
        fs.mkdir(dirname, callback);
      });
    }
  });
}

// 递归创建目录 同步方法
function mkDirsSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkDirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

module.exports = router;
